package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

 @Autowired
 UserDao userDao;

 @Override
 public boolean login(String username, String password) {
  log.debug("service_provide...u:" + username + " p:" + password);
  if ("admin".equals(username) && "123".equals(password)) {
   return true;
  } else {
   throw new BusinessRuntimeException("登录失败");
  }
 }

 @Override
 public SysUser findByUsername(String username) {
  return userDao.findByUsername(username);
 }

 //新增用户user
 @Override
 public void add(SysUser user, Integer[] roleIds) {
  //调用dao新增
  userDao.add(user);
  //调用setRelation方法设置和角色的关联
  setRelation(user.getId(), roleIds);
 }

 @Override
 public PageResult findPage(QueryPageBean pageBean) {
  PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
  Page<SysUser> page = userDao.findByCondition(pageBean.getQueryString());
  return new PageResult(page.getTotal(), page);
 }

 @Override
 public SysUser findById(Integer id) {
  return userDao.findById(id);
 }

 @Override
 public List<Integer> findRoleIdsByUserId(Integer userId) {
  return userDao.findRoleIdsByUserId(userId);
 }

 @Override
 public void edit(SysUser sysUser, Integer[] roleIds) {
  //删除所有的role关系
  userDao.delRelation(sysUser.getId());
  //维护新的关系
  setRelation(sysUser.getId(), roleIds);
  //编辑用户信息
  userDao.edit(sysUser);
 }

 @Override
 public void delById(Integer id) {
  //删除和role关系，删除user信息
  userDao.delRelation(id);
  userDao.delById(id);
 }

 //设置用户和角色的关联关系
 private void setRelation(Integer userId, Integer[] roleIds) {
  if (roleIds != null && roleIds.length > 0) {
   for (Integer roleId : roleIds) {
    userDao.setRelation(userId, roleId);
   }
  }
 }
}